package org.jeecg.modules.door.stocket;

import org.apache.http.util.TextUtils;

public class util {
    /**
     * 将十六进制的字符串转换成字节数组1
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStrToBinaryStr(String hexString) {
        if (TextUtils.isEmpty(hexString)) {
            return null;
        }
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;
        byte[] bytes = new byte[len / 2];
        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index/2] = (byte)Integer.parseInt(sub,16);
            index += 2;
        }
        return bytes;
    }
    /**
     * 将十六进制的字符串转换成字节数组2
     *
     * @param hexMessage
     * @return
     */
    public static byte[]  HexMessageToByteArray(String hexMessage) {


            // 去除空格，并将字符串分割成16进制数对
            String[] hexValues = hexMessage.split(" ");
            byte[] byteArray = new byte[hexValues.length];

            // 将每个16进制数对转换为字节
            for (int i = 0; i < hexValues.length; i++) {
                byteArray[i] = (byte) Integer.parseInt(hexValues[i], 16);
            }
            // 打印转换后的字节数组
            System.out.print("转换后的字节数组: [");
            for (byte b : byteArray) {
                System.out.print(b + " ");
            }
            System.out.println("]");
            return byteArray;

    }


    // 将16进制字符串转换为字节数组
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    /**
     * 将字节数组转换成十六进制的字符串
     *
     * @return
     */
    public static String BinaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        String result = "";
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result += hex + " ";
        }
        return result;
    }


}
